<template>
  <div>

    <video width="200" height="150" ref="preview" autoplay></video>
    <vue-baberrage
      :isShow="barrageIsShow"
      :barrageList="barrageList"
      :maxWordCount="maxWordCount"
      :throttleGap="throttleGap"
      :loop="barrageLoop"
      :boxHeight="boxHeight"
      :messageHeight="messageHeight"
      :lanesCount="lanesCount"
      :time="time"
    >
    </vue-baberrage>
    <img src="../assets/Images/login-bg.png">
    <div class="login-wrap">

      <div class="ms-title">DC教育--教师推流端</div>
      <div class="ms-login">

        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm">
          <div v-if="errorInfo" style="margin-bottom: 5px;">
            <span>{{ errInfo }}</span>
          </div>
          <el-form-item prop="name">
            <el-input v-model="ruleForm.name" placeholder="账号"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" placeholder="密码" v-model="ruleForm.password"
                      @keyup.enter.native="submitForm('ruleForm')"></el-input>
          </el-form-item>
          <el-form-item prop="validate">
            <el-input v-model="ruleForm.validate" class="validate-code" placeholder="验证码"></el-input>
            <div class="code" @click="refreshCode">
              <sidentify :identifyCode="identifyCode"></sidentify>
            </div>
          </el-form-item>
          <div class="login-btn">
            <el-button type="primary" @click="login(ruleForm)">登录</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>

</template>

<script>

const electron = require("electron");
const { ipcRenderer } = electron;
import sidentify from "../components/identify";
import Vue from "vue";
import { vueBaberrage, MESSAGE_TYPE } from "vue-baberrage";
const fs = require("fs");
const SCREEN_WIDTH = 1024;
const SCREEN_HEIGHT = 640;
Vue.use(vueBaberrage);
export default {
  name: "login",
  components: {
    sidentify,
    vueBaberrage
  },
  data() {
    return {
      recording: false,
      msg: "chenjinyin",//消息
      time: 20,//弹幕时间
      barrageIsShow: true,//弹幕是否显示
      messageHeight: 30,//消息最大高度
      boxHeight: 412,//盒子最大高度
      barrageLoop: true,//是否循环弹幕
      maxWordCount: 120,//弹幕最多字
      throttleGap: 5000,
      barrageList: [],//弹幕列表
      lanesCount: 4,
      errInfo: "",
      identifyCodes: "1234567890abcdefghijklmnopqrstuvwxyz",//验证码
      identifyCode: "",
      errorInfo: false,
      ruleForm: {
        name: "",
        password: "",
        validate: ""
      },
      rules: {
        name: [
          { required: true, message: "请输入登录名", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" }
        ],
        validate: [
          { required: true, message: "请输入验证码", trigger: "blur" }
        ]
      }
    };
  },
  //挂载
  mounted() {
    //this._playerCanvas = new PlayerCanvas(SCREEN_WIDTH, SCREEN_HEIGHT);
    this.addToList();
    this.identifyCode = "";
    this.makeCode(this.identifyCodes, 4);
  },
  methods: {
    async btnStartRecordClicked(e) {
      this._stream = new MediaStream();
      await this.attachAudioStream();
      this._cameraStream = await navigator.mediaDevices.getUserMedia({video: true, audio: false});
      this._playerCanvas.setCameraVideo(this.createVideoElementWithStream(this._cameraStream));

      this._screenStream = await navigator.mediaDevices.getUserMedia({
        audio: false,
        video: {
          mandatory: {
            chromeMediaSource: 'desktop',
            minWidth: SCREEN_WIDTH,
            maxWidth: SCREEN_WIDTH,
            minHeight: SCREEN_HEIGHT,
            maxHeight: SCREEN_HEIGHT
          }
        }
      });
      this._playerCanvas.setScreenVideo(this.createVideoElementWithStream(this._screenStream));

      let playerCanvasStream = this._playerCanvas.canvas.captureStream();
      playerCanvasStream.getTracks().forEach(t => this._stream.addTrack(t));
      this.$refs.preview.srcObject = playerCanvasStream;

      this.startRecord();
    },

    async attachAudioStream() {
      this._audioStream = await navigator.mediaDevices.getUserMedia({video: true, audio: true});
      this._audioStream.getAudioTracks().forEach(value => this._stream.addTrack(value));
    },

    btnStopRecordClicked(e) {
      this.recording = false;
      this._recorder.stop();
    },

    // createVideoElementWithStream(stream) {
    //   let video = document.createElement("video");
    //   video.autoplay = true;
    //   video.srcObject = stream;
    //   return video;
    // },
    startRecord() {
      this._recorder = new MediaRecorder(this._stream, {mimeType: "video/webm;codecs=h264"});
      this._recorder.ondataavailable = async e => {
        let path = electron.remote.dialog.showSaveDialogSync(electron.remote.getCurrentWindow(), {
          title: "保存文件",
          defaultPath: "ScreenData.webm"
        });
        fs.writeFileSync(path, new Uint8Array(await e.data.arrayBuffer()));
      };
      this._recorder.start();
      this.recording = true;
    },
    //添加弹幕列表
    addToList() {
      this.barrageList.push({
        id: ++this.currentId,
        avatar: "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3717120934,3932520698&fm=26&gp=0.jpg",
        msg: "欢迎您登录云直播推流端！",
        time: 5,
        type: MESSAGE_TYPE.NORMAL
      });
    },
    //创建子窗体
    createMinWindow() {
      console.log(1231231);
      this.$router.push({
        path: `/push`
      });
    },
    //登录
    login(ruleForm) {
      if (this.submitForm()) {
        this.$message.warning("正在登录中！！请勿重复点击按钮");
        let url = "http://39.108.215.169:10239/api/TokenAuth/Authenticate";
        this.$ajax.post(url, {
          userNameOrEmailAddress: ruleForm.name,
          password: ruleForm.password,
          verificationCode: "string",
          rememberClient: true,
          returnUrl: "string"
        }, {
          headers: {
            "accept": "text/plain",
            "Content-Type": "application/json-patch+json",
            "Authorization": this.$store.getters.token
          }
        }).then((res) => {
          console.log(res);
          if (!res.data.success) {
            this.$message.error("登录失败请检查账号密码！！");
            return;
          }
          else{
            this.$message.success("登录成功！！");
            this.$store.commit("token", res.data.result.accessToken);
            localStorage.setItem("token",res.data.result.accessToken);
            this.createMinWindow();
            this.$router.push({
              path: `/push`
            });
            self.$message.success("登录成功！陈锦银");
          }
        }).catch(err => {
          return;
        });
      }

    },
    //登录检查
    submitForm() {
      const self = this;
      self.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (self.ruleForm.validate != this.identifyCode) {
            self.errorInfo = true;
            this.refreshCode();
          }
        } else {
          return false;
        }
      });
      return true;

    },
    //注册暂时禁用
    gotoRegister() {
      this.$router.push("/register");
    },
    //随机函数
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },
    //刷新验证码
    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },
    //生成验证码
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode += this.identifyCodes[
          this.randomNum(0, this.identifyCodes.length)
          ];
      }
      console.log(this.identifyCode);
    }

  }
};
</script>

<style d>

.login-wrap {

  width: 100%;
  height: 100%;
  margin-top: 350px;

}

.ms-title {
  position: absolute;
  top: 50%;
  width: 100%;
  margin-top: -230px;
  text-align: center;
  font-size: 30px;
  color: #fff;


}

.ms-login {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 300px;
  height: 240px;
  margin: -150px 0 0 -190px;
  padding: 40px;
  border-radius: 5px;
  background: #fff;
}

.ms-login span {
  color: #ffffff;
  font-weight: bold;
}

.login-btn {
  text-align: center;
}

.login-btn button {
  width: 100%;
  height: 36px;
  color: #ffffff;
  font-weight: 100;
}

.code {
  width: 112px;
  height: 35px;
  border: 1px solid #ccc;
  float: right;
  border-radius: 2px;
  margin-top: 6%;
}

.validate-code {
  width: 136px;
  float: left;
}

.register {
  font-size: 14px;
  line-height: 30px;
  color: #999;
  cursor: pointer;
  float: right;
}

</style>